<?php

require_once 'IService.class.php';

abstract class AbstractService implements IService {

    const ZERO = 0;
    const ONE_ROW = 1;
    const SALVAR = 'Salvar';
    const SALVAR_COMO = 'SalvarComo';
    const PESQUISAR = 'Pesquisar';
    const EXCLUIR = 'Excluir';

    //Model Object
    private $model;
    //Connection Database Object
    protected $conn;

    protected function getConn() {
        return $this->conn;
    }

    /**
     * Default constructor.
     */
    public function __construct() {
        
    }

    public function getModel() {
        return $this->model;
    }

    public function setModel($model) {
        $this->model = $model;
    }

    /**
     * Start here some process.
     * @param $_GET, $_POST or $_REQUEST $objRequest
     */
    protected function init() {
        //Creating connection obj
        $this->conn = new Connection();
        //Openning the connection
        $this->conn->open();
    }

    /**
     * End here some process.
     * @param $_GET, $_POST or $_REQUEST $objRequest
     */
    protected function end() {
        //Closing the connection
        $this->conn->close();
    }

    /**
     * This method is implemented in AbstractController.
     * It is calling the other 3 methods.
     * If you want to subscribe, don't forget it.
     * init($objRequest);
     * specificExecute($objRequest);
     * end($objRequest);
     * @param $_GET, $_POST or $_REQUEST $objRequest
     */
    public final function execute() {
        $this->init();
        $this->specificExecute();
        $this->end();
    }

    /**
     * Executa as chamadas Dao para manipular o banco de dados.
     * @author Tiago <tiago.professor@gmail.com>
     */
    protected function specificExecute() {
        switch ($this->getModel()->getAction()) {
            case self::SALVAR:
                $this->executarSalvar();
                break;
            case self::SALVAR_COMO:
                $this->executarSalvarComo();
                break;
            case self::PESQUISAR:
                $this->executarPesquisa();
                break;
            case self::EXCLUIR:
                $this->executarExcluir();
                break;
        }
    }

    /**
     * Gera um array com as linhas retornadas no result.
     * @author Tiago <tiago.professor@gmail.com>
     * @return array
     */
    protected function getArrayFromResult($result) {
        $arrayRows = array();
        while ($row = $this->conn->fetchAssoc($result)) {
            $arrayRows[] = $row;
        }
        return $arrayRows;
    }

}

?>
